package com.mytest.service.impl;

import com.mytest.jwtentity.JWTResponseData;
import com.mytest.jwtentity.JWTSubject;
import com.mytest.service.LoginService;
import com.mytest.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Wulc
 * @date 2024/4/8 10:58
 * @description
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    @Qualifier("redisTemplate1")
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public JWTResponseData login(String username, String password) {
        JWTResponseData responseData = null;
        if (username.equals("wulc") && password.equals("123")) {
            JWTSubject subject = new JWTSubject(username);
            String jwtToken = JWTUtils.createJWT(UUID.randomUUID().toString(), "sxt-test-jwt",
                    username, 1 * 60 * 1000);//设置token过期时间
            redisTemplate.opsForValue().set(username, jwtToken, 60, TimeUnit.SECONDS);
            responseData = new JWTResponseData();
            responseData.setCode(200);
            responseData.setData(null);
            responseData.setMsg("登录成功");
            responseData.setToken(jwtToken);
        } else {
            responseData = new JWTResponseData();
            responseData.setCode(500);
            responseData.setData(null);
            responseData.setMsg("登录失败");
            responseData.setToken(null);
        }
        return responseData;
    }

    @Override
    public JWTResponseData loginout(String username) {
        redisTemplate.opsForValue().set(username, "");
        return new JWTResponseData(200, username, "退出登录", "");
    }
}
